﻿$(function () {
    google.maps.event.addDomListener(window, 'load', function () {
        /*地圖預設*/
        var markersArray = [];
        var mapdiv = document.getElementById('user_gmap');
        var path = "./Handler/HandlerGoogleMap.ashx";
        /*定義地圖*/
        var map = new google.maps.Map(mapdiv, MapOptions());
        /*座標預設*/
        $("#TargetLatLng").val(new google.maps.LatLng(25.03372329381502, 121.54327354159545));
        TargetLatLng = AddMarkerRClickEvent(map, markersArray, TargetLatLng);
        /*類別選項*/
        var postData = { type: "category" };
        DataRead(path, postData);
        /*品牌選項*/
        postData = { type: "brand" };
        DataRead(path, postData);
        /*change================================*/
        /*類別->商品選項*/
        $(".Category").change(function () {
            postData = {
                type: "product"
                   , category: $(this).val()
                   , brand: $(this).next().val()
                   , target: $(this).next().next().attr("id")
            };
            if ($(this).val() != -1 && $(this).next().val() != -1) {
                DataRead(path, postData);
            }
            else {
                $("#" + postData.target).empty().append("<option value='-1'>商品</option>");
            }
        });
        /*品牌->商品選項*/
        $(".Brand").change(function () {
            postData = {
                type: "product"
                   , category: $(this).prev().val()
                   , brand: $(this).val()
                   , target: $(this).next().attr("id")
            };
            if ($(this).val() != -1 && $(this).prev().val() != -1) {
                DataRead(path, postData);
            }
            else {
                $("#" + postData.target).empty().append("<option value='-1'>商品</option>");
            }
        });
        /*價格數字判斷*/
        $("#TxtPrice").change(function () {
            var Result = InputCheck($(this).val());
            if (!Result) {
                $(this).val("");
            }
        });
        /*收尋結果->移動地圖中心*/
        $("#SelectResult").change(function () {
            var str = $("#SelectResult").val()
            map.setCenter(new google.maps.LatLng(
                str.substr(1, str.indexOf(",") - 1),
                str.substr(str.indexOf(",") + 1, str.indexOf(")") - str.indexOf(",") - 1)
                ));
            map.setZoom(16);
        });
        /*地區->移動地圖中心*/
        $(".SelectArea").change(function () {
            if ($(this).val() !=-1)
            {
                var str = $(this).val();
                map.setCenter(new google.maps.LatLng(
                    str.substr(1, str.indexOf(",") - 1),
                    str.substr(str.indexOf(",") + 1, str.indexOf(")") - str.indexOf(",") - 1)
                    ));
                map.setZoom(16);
            }
        });
        /*click================================*/
        /*顯示搜尋區塊*/
        $("#btn-search").click(function () {
            ClearMarker(markersArray);
            $(".SelectArea").val(-1);
        });
        /*顯示新增Merker區塊*/
        $("#btn-add").click(function () {
            ClearMarker(markersArray);
            $("Select").val(-1);
            /*加入起始座標*/
            map = new google.maps.Map(mapdiv, MapOptions());
            AddStartMarker(map, markersArray);
            AddMarkerRClickEvent(map, markersArray);
        });
        /*新增標記*/
        $("#btn-add-price").click(function () {
            var Result3 = $("#SelectProduct2").val();
            var Result4 = $("#SelectProduct2").next(2).val();
            var Result5 = $("#SelectProduct2").next().next().val();
            if (Result3 != -1 && Result4 != "" && Result5 != "") {
                var str = $("#TargetLatLng").val();
                postData = {
                    type: "Gm"
                    , x: str.substr(1, str.indexOf(",") - 1)
                    , y: str.substr(str.indexOf(",") + 1, str.indexOf(")") - str.indexOf(",") - 1)
                    , product: Result3
                    , price: Result4
                    , info: Result5
                };
                DataInsert(path, postData);
            }
        });
        /*查詢標記*/
        $("#btn-search-price").click(function () {
            ClearMarker(markersArray);
            /*範圍判斷=========================*/
            var bounds = map.getBounds();
            var point1 = bounds.getNorthEast();//東北角
            var point2 = bounds.getSouthWest();//西南角
            var Result4 = $("#SelectProduct1").val();
            var Result5 = $("#SelectProduct1").next().val();
            var Result6 = $("#SelectProduct1").next().next().val();
            if (Result4 != -1 && Result5 != -1) {
                switch (Result5) {
                    case "1": MinPrice = 0; MaxPrice = 5000; break;
                    case "2": MinPrice = 5000; MaxPrice = 7500; break;
                    case "3": MinPrice = 7500; MaxPrice = 10000; break;
                    case "4": MinPrice = 10000; MaxPrice = 12500; break;
                    case "5": MinPrice = 12500; MaxPrice = 15000; break;
                    case "6": MinPrice = 15000; MaxPrice = 17500; break;
                    case "7": MinPrice = 17500; MaxPrice = 20000; break;
                    case "8": MinPrice = 20000; MaxPrice = 22500; break;
                    case "9": MinPrice = 22500; MaxPrice = 25000; break;
                    case "10": MinPrice = 25000; MaxPrice = 27500; break;
                    case "11": MinPrice = 27500; MaxPrice = 30000; break;
                    case "12": MinPrice = 30000; MaxPrice = 32500; break;
                    case "13": MinPrice = 32500; MaxPrice = 35000; break;
                    case "14": MaxPrice = -1; MinPrice = 35000; break;
                }
                switch (Result6) {
                    case "-1": date = 7; break;
                    case "1": date = 7; break;
                    case "2": date = 15; break;
                    case "3": date = 30; break;
                }
                postData = {
                    type: "MarkerRead"
                    , MaxX: point1.lat()
                    , MinX: point2.lat()
                    , MaxY: point1.lng()
                    , MinY: point2.lng()
                    , p: Result4
                    , MaxPrice: MaxPrice
                    , MinPrice: MinPrice
                    , Date: date
                };
                DataRead(path, postData, map, markersArray);
            }
        });
    });
    /*新增地區選項*/
    AddArea();
    /*軒哥區===================================*/
    var SearhForm = $('.left-search-container');
    var AddForm = $('.left-add-container');
    $(function () {
        showElement($(SearhForm));
    })
    function showSearhForm() {
        AddForm.hide();
        showElement($(SearhForm));
    }
    function showAddForm() {
        SearhForm.hide();
        showElement($(AddForm));
    }
    $('#btn-search').click(showSearhForm);
    $('#btn-add').click(showAddForm);
    /*=========================================*/
});
/*地圖設定*/
function MapOptions() {
    var myOptions = {
        zoom: 15,
        center: new google.maps.LatLng(25.03372329381502, 121.54327354159545),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scaleControl: true,
        minZoom: 12
    };
    return myOptions;
}
/*右鍵新增Marker事件*/
function AddMarkerRClickEvent(map, markersArray) {
    google.maps.event.addListener(map, "rightclick", function (event) {
        if ($(".left-add-container").css("display") == "block") {
            /*清除所有marker*/
            ClearMarker(markersArray);
            /*創造marker*/
            var marker_Click = new google.maps.Marker({
                map: map,
                position: event.latLng,
                title: "價格"
            });
            /*設定說明*/
            contentString = "<div><h4>說明<h4></div>";
            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });
            /*存入markerArray方便清空*/
            markersArray.push(marker_Click);
            /*給予mouseenter事件顯示title*/
            google.maps.event.addListener(marker_Click, 'mouseenter', function () {
                infowindow.open(map, marker_Click);
            });
            /*給予click事件顯示說明*/
            google.maps.event.addListener(marker_Click, 'click', function () {
                infowindow.open(map, marker_Click);
            });
            /*marker會跳動*/
            marker_Click.setAnimation(google.maps.Animation.BOUNCE);
            /*座標*/
            TargetLatLng = event.latLng;
            $("#TargetLatLng").val(event.latLng);
        }
    });
}
/*讀取資料*/
function DataRead(Path, PostData, map, markersArray) {
    $.post(Path, PostData, function (data) {
        var content = "";
        $.each(data, function (name, value) {
            switch (PostData.type) {
                case "category":
                    for (var i = 0; i < value.length ; i++) {
                        content += "<option value='" + value[i].value + "'>" + value[i].category + "</option>";
                    }
                    AddSelectOption($(".Category"), content);
                    break;
                case "brand":
                    for (var i = 0; i < value.length ; i++) {
                        content += "<option value='" + value[i].value + "'>" + value[i].brand + "</option>";
                    }
                    AddSelectOption($(".Brand"), content);
                    break;
                case "product":
                    content += "<option value='-1'>商品</option>";
                    for (var i = 0; i < value.length ; i++) {
                        content += "<option value='" + value[i].value + "'>" + value[i].product + "</option>";
                    }
                    $("#" + PostData.target).empty();
                    AddSelectOption($("#" + PostData.target), content);
                    break;
                case "MarkerRead":
                    content += "<option value='-1'>搜尋結果</option>";
                    for (var i = 0; i < value.length ; i++) {
                        AddMarker(map, markersArray, value[i].x, value[i].y, value[i].information, value[i].price);
                        content += "<option value='(" + value[i].x + "," + value[i].y + ")'>" + value[i].price + "</option>";
                    }
                    if (value.length == 0) {
                        uboxWarning("目前顯示範圍沒有符合條件資料");
                    } else {
                        $("#SelectResult").empty();
                        AddSelectOption($("#SelectResult"), content);
                    }
                    break;
            }
        });
    });
}
/*新增資料*/
function DataInsert(Path, PostData) {
    $.post(Path, PostData, function (data) {
        $.each(data, function (name, value) {
            switch (PostData.type) {
                case "Gm":
                    if (value[0].Result > 0) {
                        uboxWarning("新增成功");
                    } else {
                        uboxWarning("新增失敗");
                    }
                    break;
            }
        });
    });
}
/*新增選項*/
function AddSelectOption(TargetSelect, Option) {
    $(TargetSelect).append(Option);
}
/*檢查價格*/
function InputCheck(Target) {
    var re = /(?=.*[^0-9])/;
    if (re.test(Target)) {
        return false;
    } else {
        return true;
    }
}
/*起始座標*/
function AddStartMarker(map, markersArray) {
    var StartMarker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(25.03372329381502, 121.54327354159545),
        title: "顯示價格"
    });
    contentString = "<div><h4>起始座標<h4></div>";
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    /*給予click事件顯示說明*/
    google.maps.event.addListener(StartMarker, 'click', function () {
        infowindow.open(map, StartMarker);
    });
    infowindow.open(map, StartMarker);
    /*存入markerArray方便清空*/
    markersArray.push(StartMarker);
}
/*加Marker*/
function AddMarker(map, markersArray, x, y, information, price) {
    var Marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(x, y),
        width: 300,
        height: 300,
        title: "價錢" + price
    });
    contentString = "<div calss='MapDiv' style='width: 100px; height=80px'>價錢" + price + "<br/>" + information + "</div>";
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    /*給予click事件顯示說明*/
    google.maps.event.addListener(Marker, 'click', function () {
        infowindow.open(map, Marker);
    });
    infowindow.open(map, Marker);
    /*存入markerArray方便清空*/
    markersArray.push(Marker);
}
/*清除所有座標*/
function ClearMarker(markersArray) {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}
/*加入地區*/
function AddArea()
{
    var content = "<option value='-1'>地區</option>"
        + "<option value='(25.048181, 121.517080)'>台北</option>"
        + "<option value='(25.014046, 121.463878)'>板橋</option>"
        + "<option value='(24.989425, 121.313559)'>桃園</option>"
        + "<option value='(24.953922, 121.225637)'>中壢</option>"
        + "<option value='(24.801667, 120.971727)'>新竹</option>"
        + "<option value='(24.136746, 120.684965)'>台中</option>"
        + "<option value='(24.081745, 120.538530)'>彰化</option>"
        + "<option value='(23.711748, 120.541170)'>斗六</option>"
        + "<option value='(23.479281, 120.440859)'>嘉義</option>"
        + "<option value='(22.997159, 120.213063)'>台南</option>"
        + "<option value='(22.639644, 120.302153)'>高雄</option>"
        + "<option value='(22.669340, 120.486256)'>屏東</option>"
        + "<option value='(24.754546, 121.758263)'>宜蘭</option>"
        + "<option value='(23.992823, 121.601003)'>花蓮</option>"
        + "<option value='(22.793736, 121.123225)'>台東</option>";
    AddSelectOption($(".SelectArea"), content);
}
